#!/usr/bin/perl
use Fcntl ':flock';
use CGI qw/:standard/;

$job_dir = '/var/www/baca/jobs';
$bin = '/home/tiago/werk/baca/do_all.sh';
$web_url = '/baca/jobs';

print header;


sub get_checked {
    my $para_name = $_[0];

    $para = param($para_name);
    if ($para eq 'on') {
	return '-' . substr($para_name, 0, 1);
    }
    else {
	return '';
    }
}



sub analise_parameters {
    return TRUE;
}

sub get_job_id {
    open (BRF, '>>/tmp/baca');
    flock (BRF, LOCK_EX);
    opendir (DIR, $job_dir);
    
    $id = 0;
    foreach $entry (readdir DIR) {
	$id = $entry if $entry > $id;
    }
    closedir(DIR);
    flock (BRF, LOCK_UN);
    return $id + 1;
}


$query = param('query') . ' AND mitochondrion[TITL]';
$email = param('email');
$gene = get_checked('gene');
$trna = get_checked('trna');
$rrna = get_checked('rrna');
$stemloop = get_checked('stemloop');
$origin = get_checked('origin');
$dloop = get_checked('dloop');
$vert = get_checked('vert');

#24
if (length($query) < 28) {
  print "We don't accept queries of length smaller than 4...";
  die;
}

if ($email eq '') {
  $do_email = ''
}
else {
  $do_email = ' -e ' . $email;
}

die if (analise_parameters() != TRUE);
$id = get_job_id();
$work_dir = $job_dir . '/' . $id;
mkdir $work_dir, 0777;
chdir $work_dir;

if (fork == 0) {
#child
    open(STDIN, '/dev/null');
    open(STDOUT, '/dev/null');
    open(STDERR, '/dev/null');
    $query =~ s/\\//g;
    $query =~ s/\$//g;
    $query =~ s/"//g;
    exec "$bin $gene $trna $rrna $stemloop $origin $dloop $vert -q \"$query\" $do_email > /tmp/baca.$$";
}

#print "$bin $gene $trna $rrna $stemloop $origin $dloop $vert -q \"$query\" $do_email";

print <<EOT
<h1>BACA is working...</h1>

If you supplied an email address then you can just close this
browser window and wait for an email with the results.<br/>
<br/>
Your job id is $id, check its progression
<a href=\"$web_url/$id\">here</a>.<br/></br>

When the html directory is created the system is near completion,
just wait a few seconds and go inside it to get the mitochodrial
visualiser console.<br/>


EOT
